//引入请求文件
var util = require('../../utils/util.js');
let app = getApp();
let url = app.url;
let gobalData = app.gobalData;
let timer = null;
let count = 60;
let canSend = true;
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		goShortMessage: '获取验证码',
		ShortMessageFlag: true,
		name: "",
		avatar: "",
		gender: "",
		mobile: 0,
		mobileLength: 0,
		code: ''
	},
	onGotUserInfo(e){
		if ( this.data.code.length < 4 ) {
			wx.showToast({
				title: '验证码错误',
				icon: 'none'
			})
			return;
		}
		wx.showLoading({
			title: '拼命注册中...'
		})
		let that = this;
		wx.getUserInfo({
			success: function(res) {
				that.setData({
					name: res.userInfo.nickName,
					avatar: res.userInfo.avatarUrl,
					gender: res.userInfo.gender
				})
				let mobile = that.data.mobile; //手机号
				let code = that.data.code; //验证码
				let userInfo = {
					name: that.data.name,
					avatar: that.data.avatar,
					mobile,
					code,
					city: gobalData.city,
					gender: that.data.gender,
					openid: gobalData.openid,
					registerType: 2  // 手机号注册
				}
				util(`${url}user/register`, userInfo).then(res => {
					if (res.status == 1) {
						wx.hideLoading();
						wx.showToast({
							title: '注册成功！'
						})
						// 保存到缓存
						wx.setStorage({
							key: 'userInfo',
							data: res.content
						})
						wx.navigateBack({
							delta: 99
						})
					} else if (res.status == 0) {
						wx.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				})
			}
		})
	},
	getCode(e){
		this.setData({
			code: e.detail.value
		})
	},
	// 获取验证码
	goShortMessage() {
		if (canSend === false) {
			return;
		}
		// 手机号码验证
		let myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
		if (this.data.mobileLength != 11) {
			wx.showToast({
				title: "手机号长度有误",
				icon: "none"
			})
		} else if (!myreg.test(this.data.mobile)) {
			wx.showToast({
				title: "手机号格式错误",
				icon: "none"
			})
			return;
		} else {
			// 格式无误，调用短信验证码接口
			if (typeof(this.data.goShortMessage) == 'string') {
				//发送短信请求
				if (canSend === true) {
					util(`${url}User/sendSms`, {
						mobile: this.data.mobile
					}).then(res => {
					})
				}
				canSend = false;

				// 递归倒计时定时器
				timer = clearInterval(timer);
				count = 60;
				//设置点第一下时，数字变成60
				this.setData({
					goShortMessage: 60,
					ShortMessageFlag: false
				})
				count--;
				//执行定时器逻辑
				timer = setInterval(() => {
					if (count <= 0) {
						this.setData({
							goShortMessage: '获取验证码',
							ShortMessageFlag: true
						});
						canSend = true;
					} else {
						this.setData({
							goShortMessage: count,
							ShortMessageFlag: false
						})
						count--;
					}
				}, 1000)
			} else {
				return;
			}
		}
	},
	// 获取手机号码
	getMobile(e) {
		this.setData({
			mobile: e.detail.value,
			mobileLength: e.detail.cursor
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		// console.log(gobalData);
	}
})
